package com.buildings.activity.table;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.buildings.R;
import com.buildings.api.Api;
import com.buildings.api.Constant;
import com.buildings.base.BaseActivity;
import com.buildings.base.BaseApplication;
import com.buildings.bean.GeologicalSvyPlanningLineDbEntity;
import com.buildings.bean.GeologicalSvyPlanningLineEntity;
import com.buildings.bean.LoginBean;
import com.buildings.http.BaseCallBack;
import com.buildings.http.JsonBuilder;
import com.buildings.http.MyHttpClient;
import com.buildings.util.CustomToast;
import com.buildings.util.DialogUtils;
import com.buildings.util.FileUtil;
import com.buildings.util.HYDialogUtils;
import com.buildings.util.HYImageUtils;
import com.buildings.util.PhotoRecycleBuild;
import com.buildings.util.SPUtil;
import com.buildings.util.StringUtil;
import com.buildings.util.TabTitleBuilder;
import com.zr.earthquate.db.greendao.DaoSession;
import com.zr.earthquate.db.greendao.GeologicalSvyPlanningLineDbEntityDao;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

//地质调查规划路线-线
public class GeologicalSvyPlanningLineActivity extends BaseActivity {
    @BindView(R.id.ll_tab_title)
    LinearLayout llTabTitle;
    @BindView(R.id.rv_pics)
    RecyclerView rvPics;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right_text)
    TextView tvRightText;

    @BindView(R.id.et_objectcode)
    EditText etObjectcode;
    @BindView(R.id.et_svylinename)
    EditText etSvylinename;
    @BindView(R.id.et_purpose)
    EditText etPurpose;
    @BindView(R.id.et_svymethods)
    EditText etSvymethods;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.btn_submit)
    Button btnSubmit;

    private TabTitleBuilder tabTitleBuilder;
    private PhotoRecycleBuild photoRecycleBuild;
    private Dialog myDialog;
    private String urlArr;
    private DaoSession daoSession;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_line);
        ButterKnife.bind(this);
        daoSession = BaseApplication.getInstance().getDaoSession();
        tabTitleBuilder = new TabTitleBuilder(llTabTitle, this);
        initView();
    }

    private String type;
    private String taskId = "";
    private String projectId = "";
    private String projectName = "";
    private String taskName = "";
    private double x, y;
    private int joninType;
    private String uuid;
    private long _id = -1;
    private boolean isOnline;

    public void initView() {
        joninType = getIntent().getIntExtra("joninType", 1);
        photoRecycleBuild = new PhotoRecycleBuild(this, rvPics, joninType);
        if (joninType != 2) {
            tvTitle.setText("地质调查规划路线-线");
            tvRightText.setText("保存");
            type = getIntent().getStringExtra("type");
            taskId = getIntent().getStringExtra("taskId");
            projectId = getIntent().getStringExtra("projectId");
            projectName = getIntent().getStringExtra("projectName");
            x = getIntent().getDoubleExtra("x", 0.0);
            y = getIntent().getDoubleExtra("y", 0.0);
            isOnline = getIntent().getBooleanExtra("isOnLine", true);
            if (TextUtils.isEmpty(type)) {
                finish();
            }
            if (isOnline && TextUtils.isEmpty(taskId)){
                finish();
            }
            if (isOnline && TextUtils.isEmpty(projectId)){
                finish();
            }
            tabTitleBuilder.setLat(x);
            tabTitleBuilder.setLon(y);
            if (getIntent().hasExtra("_id")) {
                _id = getIntent().getLongExtra("_id", -1);
                setLocalData(_id);
            }
            if (1 == Constant.IS_ON_LINE){
                btnSubmit.setVisibility(View.VISIBLE);
            }else {
                btnSubmit.setVisibility(View.GONE);
            }
        } else {
            isOnline = getIntent().getBooleanExtra("isOnLine", false);
            if (1 == Constant.IS_ON_LINE){
                tvTitle.setText("地质调查规划路线-线详情");
                uuid = getIntent().getStringExtra("uuid");
                tabTitleBuilder.setEnabled();
                setEnableFalse();
                getDetailHttp();
                btnSubmit.setVisibility(View.GONE);
            }else {
                tvTitle.setText("地质调查规划路线-线");
                tvRightText.setText("保存");
                uuid = getIntent().getStringExtra("uuid");
                if (getIntent().hasExtra("_id")) {
                    _id = getIntent().getLongExtra("_id", -1);
                    setLocalData(_id);
                }
                btnSubmit.setVisibility(View.GONE);
            }
        }
    }

    public void setLocalData(long a) {
        if (a == -1) {
            return;
        }
        List<GeologicalSvyPlanningLineDbEntity> students = daoSession.loadAll(GeologicalSvyPlanningLineDbEntity.class);
        for (GeologicalSvyPlanningLineDbEntity geologicalSvyPlanningLineDbEntity : students) {
            if (a == geologicalSvyPlanningLineDbEntity.get_id()) {
                setDetail(geologicalSvyPlanningLineDbEntity);
            }
        }
    }

    private GeologicalSvyPlanningLineDbEntity geologicalSvyPlanningLineDbEntity;

    public void setDetail(GeologicalSvyPlanningLineDbEntity bean) {
        this.geologicalSvyPlanningLineDbEntity = bean;

        tabTitleBuilder.setDetailText(bean.getProvince(), bean.getCity()
                , bean.getArea(), bean.getLat(), bean.getLon(), bean.getTown());

        etObjectcode.setText(StringUtil.isNull(bean.getId()));
        etSvylinename.setText(StringUtil.isNull(bean.getSvylinename()));
        etPurpose.setText(StringUtil.isNull(bean.getPurpose()));
        etSvymethods.setText(StringUtil.isNull(bean.getSvymethods()));
        etRemark.setText(StringUtil.isNull(bean.getCommentInfo()));
        if (!TextUtils.isEmpty(bean.getExtends7())) {
            String[] arr = bean.getExtends7().split(",");
            List<Uri> list = new ArrayList<>();
            for (int i = 0; i < arr.length; i++) {
                File file = new File(arr[i]);
                Uri uri = Uri.fromFile(file);
                list.add(uri);
            }
            photoRecycleBuild.updataAdapter(list);
        }
    }

    private void setEnableFalse() {
        etObjectcode.setEnabled(false);
        etSvylinename.setEnabled(false);
        etPurpose.setEnabled(false);
        etSvymethods.setEnabled(false);
        etRemark.setEnabled(false);
    }

    @OnClick({R.id.iv_back, R.id.tv_right_text, R.id.btn_submit,R.id.iv_id_hint})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_right_text:
                //TODO 调用保存表单接口
                save();
                break;
            case R.id.btn_submit:
                submit();
                break;
            case R.id.iv_id_hint:
                HYDialogUtils.showCommonAlertDialog(this, "长度17位，前9位，行政区划代码6位+3位专题号，后8位自定义编码，字母数字均可，不足8位#补齐\n" +
                                "3位专题号，用户自己设置。一般就是100，101，102...,201,202"
                        , new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                            }
                        });
                break;
        }
    }

    public void save() {
        GeologicalSvyPlanningLineDbEntity geologicalSvyPlanningLineDbEntity = new GeologicalSvyPlanningLineDbEntity();
        if (null == daoSession) {
            daoSession = BaseApplication.getInstance().getDaoSession();
        }
        String province = tabTitleBuilder.getProvinceStr();
        String city = tabTitleBuilder.getCityStr();
        String area = tabTitleBuilder.getAreaStr();
        String lat = tabTitleBuilder.getLatStr();
        String lon = tabTitleBuilder.getLonStr();
        String buildingAddress = tabTitleBuilder.getBuilderAdressStr();
        String objectcode = etObjectcode.getText().toString().trim();
        String svylinename = etSvylinename.getText().toString().trim();
        String purpose = etPurpose.getText().toString().trim();
        String svymethods = etSvymethods.getText().toString().trim();
        String remark = etRemark.getText().toString().trim();
        if (TextUtils.isEmpty(province)) {
            Toast("请录入地区");
            return;
        }
        if (TextUtils.isEmpty(city)) {
            Toast("请录入地区");
            return;
        }
        if (TextUtils.isEmpty(area)) {
            Toast("请录入地区");
            return;
        }
        if (TextUtils.isEmpty(lon)) {
            Toast("请录入纬度");
            return;
        }
        if (TextUtils.isEmpty(lat)) {
            Toast("请录入经度");
            return;
        }
        if (TextUtils.isEmpty(buildingAddress)) {
            Toast("请录入详细地址");
            return;
        }
        if (TextUtils.isEmpty(objectcode)) {
            Toast("请录入编号");
            return;
        }
        if (objectcode.length() != 17){
            Toast("请录入正确的编号");
            return;
        }
        geologicalSvyPlanningLineDbEntity.setProvince(province);
        geologicalSvyPlanningLineDbEntity.setCity(city);
        geologicalSvyPlanningLineDbEntity.setArea(area);
        geologicalSvyPlanningLineDbEntity.setLat(lat);
        geologicalSvyPlanningLineDbEntity.setLon(lon);
        geologicalSvyPlanningLineDbEntity.setTown(buildingAddress);
        geologicalSvyPlanningLineDbEntity.setId(objectcode);
        geologicalSvyPlanningLineDbEntity.setSvylinename(svylinename);
        geologicalSvyPlanningLineDbEntity.setPurpose(purpose);
        geologicalSvyPlanningLineDbEntity.setSvymethods(svymethods);
        geologicalSvyPlanningLineDbEntity.setCommentInfo(remark);
        if (Constant.IS_ON_LINE == 1) {
            geologicalSvyPlanningLineDbEntity.setTaskId(taskId);
            geologicalSvyPlanningLineDbEntity.setProjectId(projectId);
            geologicalSvyPlanningLineDbEntity.setProjectName(projectName);
            geologicalSvyPlanningLineDbEntity.setTaskName(taskName);
        }
        if (photoRecycleBuild.getSrcList().size() != 0) {
            String url = "";
            for (int i = 0; i < photoRecycleBuild.getSrcList().size(); i++) {
                if (TextUtils.isEmpty(url)) {
                    url = FileUtil.uriToFile(photoRecycleBuild.getSrcList().get(i), activity).getPath();
                } else {
                    url = url + "," + FileUtil.uriToFile(photoRecycleBuild.getSrcList().get(i), activity).getPath();
                }
            }
            geologicalSvyPlanningLineDbEntity.setExtends7(url);
        }
        if (-1 != _id) {
            geologicalSvyPlanningLineDbEntity.set_id(_id);
        }
        daoSession.insertOrReplace(geologicalSvyPlanningLineDbEntity);
        CustomToast.showToast(GeologicalSvyPlanningLineActivity.this, "保存成功");
        finish();
    }

    public void submit() {
        String province = tabTitleBuilder.getProvinceStr();
        String city = tabTitleBuilder.getCityStr();
        String area = tabTitleBuilder.getAreaStr();
        String lat = tabTitleBuilder.getLatStr();
        String lon = tabTitleBuilder.getLonStr();
        String buildingAddress = tabTitleBuilder.getBuilderAdressStr();

        String objectcode = etObjectcode.getText().toString().trim();
        String svylinename = etSvylinename.getText().toString().trim();
        String purpose = etPurpose.getText().toString().trim();
        String svymethods = etSvymethods.getText().toString().trim();
        String remark = etRemark.getText().toString().trim();

        if (TextUtils.isEmpty(province)) {
            Toast("请录入地区");
            return;
        }
        if (TextUtils.isEmpty(city)) {
            Toast("请录入地区");
            return;
        }
        if (TextUtils.isEmpty(area)) {
            Toast("请录入地区");
            return;
        }
        if (TextUtils.isEmpty(lon)) {
            Toast("请录入纬度");
            return;
        }
        if (TextUtils.isEmpty(lat)) {
            Toast("请录入经度");
            return;
        }
        if (TextUtils.isEmpty(buildingAddress)) {
            Toast("请录入详细地址");
            return;
        }
        if (TextUtils.isEmpty(objectcode)) {
            Toast("请录入编号");
            return;
        }
        if (objectcode.length() != 17){
            Toast("请录入正确的编号");
            return;
        }
        if (myDialog == null) {
            myDialog = DialogUtils.showRefreshDialog(activity);
        } else {
            myDialog.show();
        }

        DialogUtils.showIOSDialog(activity, "提示", "", "", "", ""
                , new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (null != myDialog)
                            myDialog.dismiss();
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        submit();
                        photoRecycleBuild.submitImage(photoRecycleBuild.getSrcList(), 1, new PhotoRecycleBuild.ImageCallBack() {
                            @Override
                            public void onCallBack(String url) {
                                GeologicalSvyPlanningLineActivity.this.urlArr = url;

                                JsonBuilder jsonBuilder = new JsonBuilder(GeologicalSvyPlanningLineActivity.this);
                                jsonBuilder.put("province", province);
                                jsonBuilder.put("city", city);
                                jsonBuilder.put("area", area);
                                jsonBuilder.put("lat", lon);
                                jsonBuilder.put("lon", lat);
                                jsonBuilder.put("town", buildingAddress);
                                //type,taskId,projectId
                                jsonBuilder.put("userId", SPUtil.get("userId", ""));
                                jsonBuilder.put("type", type);
                                jsonBuilder.put("taskId", taskId);
                                jsonBuilder.put("projectId", projectId);
                                jsonBuilder.put("projectName", projectName);
                                jsonBuilder.put("taskName", taskName);
                                jsonBuilder.put("id", objectcode);
                                jsonBuilder.put("svylinename", svylinename);
                                jsonBuilder.put("purpose", purpose);
                                jsonBuilder.put("svymethods", svymethods);
                                jsonBuilder.put("commentInfo", remark);
                                jsonBuilder.put("extends7", urlArr);
                                jsonBuilder.put("createUser", SPUtil.get("userId", ""));
                                MyHttpClient
                                        .newBuilder()
                                        .post()
                                        .url(Api.DZDCGHLX_1_SAVE)
                                        .addParam(jsonBuilder.toJsonString())
                                        .build()
                                        .enqueue(new BaseCallBack<LoginBean>() {
                                            @Override
                                            public void onSuccess(LoginBean bean) {
                                                super.onSuccess(bean);
                                                if (bean.getCode() == 200) {
                                                    if (-1 != _id && null != geologicalSvyPlanningLineDbEntity) {
                                                        try {
                                                            daoSession.delete(geologicalSvyPlanningLineDbEntity);
                                                        } catch (Exception e) {
                                                            e.printStackTrace();
                                                        }
                                                    }
                                                    CustomToast.showToast(GeologicalSvyPlanningLineActivity.this, "提交成功");
                                                    finish();
                                                }
                                                if (myDialog != null)
                                                    myDialog.dismiss();
                                            }

                                            @Override
                                            public void onFailure(Call call, IOException e) {
                                                super.onFailure(call, e);
                                                if (myDialog != null)
                                                    myDialog.dismiss();
                                                CustomToast.showToast(GeologicalSvyPlanningLineActivity.this, "网络异常");
                                            }

                                            @Override
                                            public void onError(int code) {
                                                super.onError(code);
                                                if (myDialog != null)
                                                    myDialog.dismiss();
                                                CustomToast.showToast(GeologicalSvyPlanningLineActivity.this, "网络异常");
                                            }
                                        });
                            }
                        });
                    }
                }, "提交后不能再修改");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case HYImageUtils.REQUEST_CODE_FROM_CAMERA:
                List<Uri> list_1 = new ArrayList<>();
                list_1.add(HYImageUtils.imageUriFromCamera);
                photoRecycleBuild.updataAdapter(list_1);
                break;
            case HYImageUtils.REQUEST_CODE_FROM_ALBUM:
                ArrayList<String> files = data.getStringArrayListExtra("files");
                if (files == null || files.size() == 0) {
                    return;
                }
                List<Uri> list_2 = new ArrayList<>();
                for (String file : files) {
                    list_2.add(Uri.fromFile(new File(file)));
                }
                photoRecycleBuild.updataAdapter(list_2);
                // submitImage(list_2, correctTypeListEntity.getFieldList().get(lastClickItemPosition));
                break;
        }
    }

    public void getDetailHttp() {
        if (myDialog == null) {
            myDialog = DialogUtils.showRefreshDialog(activity);
        } else {
            myDialog.show();
        }
        String url = Api.DZDCGHLX_1_SAVE + "/" + uuid;
        MyHttpClient
                .newBuilder()
                .get()
                .url(url)
                .build()
                .enqueue(new BaseCallBack<GeologicalSvyPlanningLineEntity>() {
                    @Override
                    public void onSuccess(GeologicalSvyPlanningLineEntity bean) {
                        super.onSuccess(bean);
                        if (bean.getCode() == 200) {
                            setDetailData(bean);
                        }
                        if (myDialog != null)
                            myDialog.dismiss();
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                        if (myDialog != null)
                            myDialog.dismiss();
                        CustomToast.showToast(GeologicalSvyPlanningLineActivity.this, "网络异常");
                    }

                    @Override
                    public void onError(int code) {
                        super.onError(code);
                        if (myDialog != null)
                            myDialog.dismiss();
                        CustomToast.showToast(GeologicalSvyPlanningLineActivity.this, "网络异常");
                    }
                });
    }

    private void setDetailData(GeologicalSvyPlanningLineEntity bean) {
        tabTitleBuilder.setDetailText(bean.getData().getProvince(), bean.getData().getCity()
                , bean.getData().getArea(), bean.getData().getLat(), bean.getData().getLon(), bean.getData().getTown());

        etObjectcode.setText(StringUtil.isNull(bean.getData().getId()));
        etSvylinename.setText(StringUtil.isNull(bean.getData().getSvylinename()));
        etPurpose.setText(StringUtil.isNull(bean.getData().getPurpose()));
        etSvymethods.setText(StringUtil.isNull(bean.getData().getSvymethods()));
        etRemark.setText(StringUtil.isNull(bean.getData().getCommentInfo()));
        photoRecycleBuild.setHttpUrl(bean.getData().getExtends7());
    }
}
